import React, { useEffect, useRef, useState } from 'react'
import Header from "../../components/Header";
import { LeftOutline } from "antd-mobile-icons"
import './index.scss'
import { useNavigate } from 'react-router-dom';
//链接服务器
const user_id = 1 
const server_id= 124124 
const ws = new WebSocket(`ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`)
function Chat() { 
  const [chatList,setChatList]=useState([])
  const [message,setMessage]=useState('')
  const srcollMsg=useRef()
  const navigate=useNavigate()

   useEffect(()=>{
     let token = localStorage.getItem('token')
     if(!token){
      navigate('/login')
     }
   },[])

   //发送信息
   const submit=()=>{ 
      ws.send(
        JSON.stringify({
           type:'addMessage',
           data:{
            user_id,
            server_id,
            message
           }
        })
      )
   }
   useEffect(()=>{
    //是否链接成功
      ws.addEventListener('open',()=>{
        console.log('链接成功')
        //获取历史记录
        ws.send(
          JSON.stringify({
            type:'getChatList'
          })
        )
      })
   //监听信息
      ws.addEventListener('message',(res)=>{
         console.log(JSON.parse(res.data))
         const {data,type}=JSON.parse(res.data)
         if(type==='getChatList'){
            setChatList(data)
         }else if(type==='addMessage'){
             setChatList(prev=>[...prev,data])
         }
      })
   },[])
    
   useEffect(()=>{
     srcollMsg.current.scrollTop=1000000000
   },[chatList])
   

  return (
    <div>
        {/* 头部组件 */}
      <Header left={<LeftOutline />} title="在线咨询"></Header>

      <div className="chat" ref={srcollMsg}>
         <div className="item">
          {
            chatList.map((v,i)=>{
              const diro = "chat-item-" + (v.dir===1?'right':'left')
              const avatar = v.dir===1 ? v.user_avatar:v.server_avatar
              return (
                <div className={diro} key={i}>
                <div className="img">
                  <img src={avatar} alt="" />
                </div>

                <div className="content">
                    <div className="text">
                       {v.message}
                    </div>
                </div>
            </div>
              )
            })
          }
           


             
     

          <div className="input">
             <input type="text"  value={message} onChange={(e)=>setMessage(e.target.value)} />
             <button onClick={submit} disabled={message===''}>发送</button>
          </div>

         </div>
      </div>
    </div>
  )
}

export default Chat
